<template>
  <div class="tw-libsearch" :style="{borderColor: borderColor}">
    <input type="text" :value="value" :style="{paddingRight: inputPaddingLeft, fontSize: fontSize, color: color}" @input="$emit('input', $event.target.value)" :placeholder="placeholder" />
    <div class="tw-libsearch-btn" @click="handleSearch">
      <i class="icon iconfont" :style="{fontSize: iconFontSize, color: iconColor}">&#xe605;</i>
    </div>
  </div>
</template>

<script>
import props from './props'

export default {
  name: 'header-navigate',

  props,

  computed: {
    inputPaddingLeft () {
      return parseInt(this.iconFontSize) + 15 + 'px'
    },

    style () {
      return {
        iconHoverColor: this.iconHoverColor,
        iconBgColor: this.iconBgColor
      }
    }
  },

  methods: {
    handleSearch () {
      this.$emit('search', this.value)
    },

    setStyle () {
      // ::root 表示组件根元素选择器
      let style = `
        ::root .tw-libsearch-btn:hover .iconfont {
          color: ${this.iconHoverColor} !important;
        }
      `
      if (this.iconBgColor) {
        style = `
          ::root .tw-libsearch-btn {
            background-color: ${this.iconBgColor};
          }

          ::root .tw-libsearch-btn:hover .icon{
            color: ${this.iconHoverColor} !important;
          }
        `
      }

      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    }
  },

  mounted () {
    this.setStyle()
  },

  watch: {
    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
